<template>
  <!-- 图表容器，必须指定宽高 -->
  <div id="echartsLeft" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import {ref, onMounted, onBeforeUnmount} from 'vue';
import * as echarts from 'echarts';
import { watch } from 'vue'
import { useStore } from 'vuex'

const store = useStore()
let myChart = ref(null);
let option=ref(null);
// 绘制图表
const drawChart = (dataSet) => {
  const chartDom = document.getElementById('echartsLeft');
  myChart = echarts.init(chartDom);
  option = {
    xAxis: {
      type: 'category',
      data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: dataSet,
        type: 'line'
      }
    ]
  };
  option && myChart.setOption(option);
}
// 生成随机数组的函数
const generateRandomArray=(length) =>{
  const arr = [];
  for (let i = 0; i < length; i++) {
    // 生成100-300之间的随机整数
    const randomNum = Math.floor(Math.random() * 201) + 100;
    arr.push(randomNum);
  }
  return arr;
}

//在组件初始化的时候执行
onMounted(() => {
  drawChart(generateRandomArray(7))
});

watch(
    () => store.state.targetVariable,
    (newValue, oldValue) => {
      console.log('状态变化:', { oldValue, newValue })
      option.series[0].data=generateRandomArray(7)
      myChart.setOption(option, true)
    }
)
</script>

<style scoped>
</style>
